package com.walter.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.walter.common.PageVO;
import com.walter.config.BaiduApiInfo;
import com.walter.entity.DayVisit;
import com.walter.exception.LogicException;
import com.walter.mapper.DayVisitMapper;
import com.walter.model.query.DayVisitQuery;
import com.walter.util.Kv;
import com.walter.util.MyCommon;
import com.walter.util.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * @author ：ch
 * @date ：Created in 2021/5/25
 * @description：
 * @modified By：
 * @version: 1.0
 */
@Service
@Slf4j
public class DayVisitService {
    @Autowired
    private DayVisitMapper dayVisitMapper;

    @Autowired
    private BaiduApiInfo baiduApiInfo;

    // find
    public PageVO<DayVisit> find(DayVisitQuery query){
        return Optional.of(query)
                .map(q -> new Page<DayVisit>(q.getPage().getPageNum(),q.getPage().getPageSize()))
                .map(p -> new PageVO<>(p.setRecords(dayVisitMapper.find(p, BeanUtil.beanToMap(query)))))
                .get();
    }

    // insertRecord
    @Transactional
    public Integer insertRecord(){
        //获取request
        HttpServletRequest request = MyCommon.getHttpServletRequest();
        String ip = "117.89.22.234";//方便 baiduApi 测试
        if (SpringUtil.getActiveProfile().equals("prod")) {
            log.info("The active profile is : {}",SpringUtil.getActiveProfile());
            ip = MyCommon.getRemoteIP(request);
        }
        Date now = new Date();
        List<DayVisit> existDayVisit = dayVisitMapper.selectList(
                new EntityWrapper<DayVisit>().eq(DayVisit.IP,ip).and()
                        .between(DayVisit.CREATE_TIME,DateUtil.beginOfDay(now),DateUtil.endOfDay(now)));
        if (CollUtil.isNotEmpty(existDayVisit)){
            return null;
        }
        DayVisit dayVisit = new DayVisit().setCreateTime(now).setIp(ip);
        try { // todo 可以提取出公共代码
            String getURL = String.format(baiduApiInfo.getGetLocationByIpURL(), ip,baiduApiInfo.getAk());
            String retJsonStr = HttpUtil.get(getURL);
            JSONObject jsonObject = JSONUtil.parseObj(retJsonStr);
            log.info("response from {} is {}",getURL,jsonObject.toStringPretty());
            if (Objects.isNull(jsonObject.getJSONObject("content")))
                // 百度开放平台ip定位接口暂不支持定位国外
                dayVisit.setLocation("国外");
            else {
                String location = jsonObject.getJSONObject("content").getStr("address");
                dayVisit.setLocation(location);
            }
        }
        catch (Exception e){
            log.info("{}",e);
            throw new LogicException(e.getMessage());
        }
        return dayVisitMapper.insert(dayVisit);
    }

    // findVisitNumInfo
    public Kv findVisitNumInfo(){
        Date now = new Date();
        List<DayVisit> dayVisitList = dayVisitMapper.selectList(
                new EntityWrapper<DayVisit>().between(DayVisit.CREATE_TIME,DateUtil.beginOfDay(now),DateUtil.endOfDay(now))
        );
        Integer totalVisitNum = dayVisitMapper.selectCount(null);
        Kv retVal = new Kv().set("date", DateUtil.format(now,"yyyy-MM-dd"))
                .set("dayVisitNum",0) // 日访问量
                .set("totalVisitNum",totalVisitNum); // 累计访问量
        Optional.ofNullable(dayVisitList).ifPresent(dayVisit -> retVal.set("dayVisitNum",dayVisit.size()));
        return retVal;
    }

}
